//
//  OldUploadGroupPhotoViewController.m
//  laonianbangSupport
//
//  Created by 勇拓 李 on 18/3/5.
//  Copyright © 2018年 zaiyou. All rights reserved.
//

#import "OldUploadGroupPhotoViewController.h"
#import "VPImageCropperViewController.h"
#import "oldImage.h"
#import "QNuploader.h"
#import "OrderInfoViewController.h"

@interface OldUploadGroupPhotoViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate,VPImageCropperDelegate>

@property (weak, nonatomic) IBOutlet UIButton *btn_startSever;
@property (weak, nonatomic) IBOutlet UIImageView *upload_img;

@end

@implementation OldUploadGroupPhotoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initView];
    [self initData];
    QiNiuShareInstance;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - initView
- (void)initView
{
    _btn_startSever.layer.cornerRadius = 6.f;
    
    self.navigationItem.title = @"上传合影";

    UITapGestureRecognizer *tapViewCA = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(getPhoto:)];
    [_upload_img addGestureRecognizer:tapViewCA];
    _upload_img.userInteractionEnabled = YES;
    [_btn_startSever addTarget:self action:@selector(btn_start_tapped:) forControlEvents:UIControlEventTouchDown];
}

#pragma mark - initData
- (void)initData
{
    
}

#pragma mark - getHeadImg
- (void)getPhoto:(UITapGestureRecognizer *)tap
{
    WeakSelf
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle: UIAlertControllerStyleActionSheet];
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    
    UIAlertAction *photoAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [weakSelf selectFormPhotos];
    }];
    
    UIAlertAction *pictureAction = [UIAlertAction actionWithTitle:@"从相册中选取" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [weakSelf selectFormPicture];
    }];
    
    [alertController addAction:cancelAction];
    
    [alertController addAction:photoAction];
    
    [alertController addAction:pictureAction];
    
    [self presentViewController:alertController animated:YES completion:nil];
}

- (void)selectFormPhotos
{
    // 拍照
    if ([self isCameraAvailable] && [self doesCameraSupportTakingPhotos]) {
        UIImagePickerController *controller = [[UIImagePickerController alloc] init];
        controller.sourceType = UIImagePickerControllerSourceTypeCamera;
        if ([self isFrontCameraAvailable]) {
            controller.cameraDevice = UIImagePickerControllerCameraDeviceFront;
        }
        NSMutableArray *mediaTypes = [[NSMutableArray alloc] init];
        [mediaTypes addObject:(__bridge NSString *)kUTTypeImage];
        controller.mediaTypes = mediaTypes;
        controller.delegate = self;
        [self presentViewController:controller
                           animated:YES
                         completion:^(void){
                             NSLog(@"Picker View Controller is presented");
                         }];
    }
}

- (void)selectFormPicture
{
    // 从相册中选取
    if ([self isPhotoLibraryAvailable]) {
        UIImagePickerController *controller = [[UIImagePickerController alloc] init];
        controller.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        NSMutableArray *mediaTypes = [[NSMutableArray alloc] init];
        [mediaTypes addObject:(__bridge NSString *)kUTTypeImage];
        controller.mediaTypes = mediaTypes;
        controller.delegate = self;
        [self presentViewController:controller
                           animated:YES
                         completion:^(void){
                             NSLog(@"Picker View Controller is presented");
                         }];
    }
}

#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    [picker dismissViewControllerAnimated:YES completion:^() {
        UIImage *portraitImg = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
        portraitImg = [oldImage imageByScalingToMaxSize:portraitImg];
        // present the cropper view controller
        VPImageCropperViewController *imgCropperVC = [[VPImageCropperViewController alloc] initWithImage:portraitImg cropFrame:CGRectMake(0, 100.0f, self.view.frame.size.width, self.view.frame.size.width) limitScaleRatio:3.0];
        imgCropperVC.delegate = self;
        [self presentViewController:imgCropperVC animated:YES completion:^{
            // TO DO
        }];
    }];
}

- (void)imageCropper:(VPImageCropperViewController *)cropperViewController didFinished:(UIImage *)editedImage {
    [self editPhoto:editedImage];
    [cropperViewController dismissViewControllerAnimated:NO completion:^{
    }];
    
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:^(){
    }];
}

- (void)imageCropperDidCancel:(VPImageCropperViewController *)cropperViewController {
    [cropperViewController dismissViewControllerAnimated:YES completion:^{
    }];
}

#pragma mark -上传合照
- (void)editPhoto:(UIImage *)editedImage
{
    _upload_img.image = editedImage;
}

- (void)btn_start_tapped:(id)sender
{
    if ([oldImage twoPicIsEqual:_upload_img.image image:[UIImage imageNamed:@"上传图片"]]) {
        [oldHub warningUser:@"请上传合照！"];
        return;
    }
    
    WeakSelf
    
    [oldHub waiting:@"上传合照中.."];
    
    NSString *url = [oldImage getImagePath:[oldImage compressImage:_upload_img.image ratio:1.0]];
    [QiNiuShareInstance uploadImageToQNFilePath:url type:Image_file block:^(NSString *url) {
        if (url) {
            [weakSelf gotoUploadPhoto:url];
        }
        else
        {
            [oldHub warningUser:@"图片上传失败,请重试"];
        }
    }];
}

- (void)gotoUploadPhoto:(NSString *)url
{
    WeakSelf
    
    NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys: _orderInfo.oid, @"oid", url, @"photoUrl", nil];
    
    [OLDNetWork httpRequestWithPostPut:URL_StartOrder params:params success:^(NSDictionary *dic) {
        [oldHub warningUserAfterJump:@"服务已开始" time:1.0];
        
        UIViewController *vc = weakSelf.navigationController.viewControllers[[weakSelf.navigationController.viewControllers count] - 2];
        
        if ([vc isKindOfClass:[OrderInfoViewController class]]) {
            OrderInfoViewController *oldVc = (OrderInfoViewController *)vc;
            oldVc.orderInfo = [[oldOrderInfo alloc] initWithDictionary:dic];
        }
        [weakSelf.navigationController popViewControllerAnimated:YES];
    } error:^(NSString *error) {
        [oldHub warningUser:error];
    }];
}

#pragma mark camera utility

- (BOOL) doesCameraSupportTakingPhotos {
    return [self cameraSupportsMedia:(__bridge NSString *)kUTTypeImage sourceType:UIImagePickerControllerSourceTypeCamera];
}

- (BOOL) isCameraAvailable{
    return [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
}

- (BOOL) isFrontCameraAvailable {
    return [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceFront];
}

- (BOOL) isPhotoLibraryAvailable{
    return [UIImagePickerController isSourceTypeAvailable:
            UIImagePickerControllerSourceTypePhotoLibrary];
}

- (BOOL) cameraSupportsMedia:(NSString *)paramMediaType sourceType:(UIImagePickerControllerSourceType)paramSourceType{
    __block BOOL result = NO;
    if ([paramMediaType length] == 0) {
        return NO;
    }
    NSArray *availableMediaTypes = [UIImagePickerController availableMediaTypesForSourceType:paramSourceType];
    [availableMediaTypes enumerateObjectsUsingBlock: ^(id obj, NSUInteger idx, BOOL *stop) {
        NSString *mediaType = (NSString *)obj;
        if ([mediaType isEqualToString:paramMediaType]){
            result = YES;
            *stop= YES;
        }
    }];
    return result;
}

@end
